package com.example.sharesinfo.ui;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import cn.bmob.v3.exception.BmobException;
import de.hdodenhof.circleimageview.CircleImageView;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sharesinfo.R;
import com.example.sharesinfo.adapter.CommonAdapter;
import com.example.sharesinfo.adapter.CommonViewHolder;
import com.example.sharesinfo.base.BaseApp;
import com.example.sharesinfo.base.BaseUIActivity;
import com.example.sharesinfo.bean.PersonalCenterBean;
import com.example.sharesinfo.bmob.BmobManager;
import com.example.sharesinfo.entity.Constants;
import com.example.sharesinfo.helper.ActivityHelper;
import com.example.sharesinfo.helper.FileHelper;
import com.example.sharesinfo.helper.GlideHelper;
import com.example.sharesinfo.manager.DialogManager;
import com.example.sharesinfo.model.TalkModel;
import com.example.sharesinfo.utils.LogUtils;
import com.example.sharesinfo.utils.OkHttpUtils;
import com.example.sharesinfo.utils.SpUtils;
import com.example.sharesinfo.view.DialogView;
import com.example.sharesinfo.view.LodingView;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.squareup.leakcanary.RefWatcher;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PersonalCenterActivity extends BaseUIActivity implements View.OnClickListener {
    //二维码结果
    private static final int REQUEST_CODE = 1235;
    private final static String LogTag = "PersonalCenterActivity:";
    private static final int QUERY_USER_CODE = 1004;
    private static final int GetMyTalkListSuccess = 1005;
    private static final int GetMyTalkListFailed = 1006;
    private PersonalCenterBean mUser;
    private boolean isScan = false;
    private boolean isPut = false;
    private ImageButton ib_return;
    private ImageButton ib_scan;
    private ImageButton ib_editable;
    private CircleImageView headImage;
    private String imageUrl;
    private CheckBox personal_focus_on;
    private CheckBox personal_talk;
    private EditText et_user_name;
    private EditText et_user_remark;
    private TextView tv_stockAge;
    private TextView tv_follow_number;
    private TextView tv_fans_number;
    private TextView tv_talk_number;
    private TextView tv_coin_number;
    private TextView tv_sumMoney;
    //头像文件
    private File uploadPhotoFile;
    private int flag = 0;
    //头像选择框
    private DialogView mPhotoDialog;
    private TextView tv_camera;
    private TextView tv_ablum;
    private TextView tv_photo_cancel;
    //性别选择框
    private DialogView mSexDialog;
    private TextView tv_boy;
    private TextView tv_girl;
    private TextView tv_sex_cancel;
    private TextView tv_user_sex;
    //二维码
    private ImageButton ib_qr;
    //更新用户信息
    private static final int UPDATESUCCESS = 1001;
    private static final int UPDATEFailed = 1002;
    private LodingView mLodingView;
    //个人说说
    private LinearLayout ll_dialog;
    private View item_empty_view;
    private RecyclerView mTalkView;
    private List<TalkModel> mList = new ArrayList<>();
    private CommonAdapter<TalkModel> mTalkAdapter;
    //TalkId=***&UserId=***
    private String SendTalkPraiseUrl = "http://119.23.221.142/api/talk/SendTalkPraise?";
    private Map<String, String> praiseDatas = new HashMap<>();
    //TalkId=***&UserId=***
    private String CancelTalkPraiseURl = "http://119.23.221.142/api/talk/CancelTalkPraise?";
    private Map<String, String> CancelPraiseDatas = new HashMap<>();
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 200:
                    PersonalCenterBean result = (PersonalCenterBean) msg.obj;
                    PersonalCenterActivity.startActivity(PersonalCenterActivity.this, result, true);
                    break;
                case 404:
                    break;
                case UPDATESUCCESS:
                    isPut = false;
                    mLodingView.hide();
                    SpUtils.getInstance().putString(Constants.SP_USER_IMAGE_URL, imageUrl);
                    Toast.makeText(PersonalCenterActivity.this, "更新成功", Toast.LENGTH_SHORT).show();
                    break;
                case UPDATEFailed:
                    Toast.makeText(PersonalCenterActivity.this, "更新失败", Toast.LENGTH_SHORT).show();
                    break;
                case QUERY_USER_CODE:
                    PersonalCenterBean result1 = (PersonalCenterBean) msg.obj;
                    PersonalCenterActivity.startActivity(PersonalCenterActivity.this, result1, false);
                    break;
                case GetMyTalkListSuccess:
                    if (mList.size() > 0) {
                        mList.clear();
                    }
                    JSONArray array = (JSONArray) msg.obj;
                    if (array.length() > 0) {
                        //有说说
                        for (int i = 0; i < array.length(); i++) {
                            TalkModel model = new TalkModel();
                            try {
                                JSONObject object = array.getJSONObject(i);
                                model.setId(Integer.parseInt(object.getString("Id")));
                                model.setImageUrl(object.getString("ImageUrl"));
                                model.setUserId(Integer.parseInt(object.getString("UserId")));
                                model.setUsername(object.getString("Username"));
                                model.setStockAge(object.getString("StockAge"));
                                model.setTalkTime(object.getString("TalkTime"));
                                model.setContent(object.getString("Content"));
                                model.setPictureUrl(object.getString("PictureUrl"));
                                LogUtils.i(LogTag + "图片链接："+object.getString("PictureUrl"));
                                model.setReadNumber(object.getString("ReadNumber"));
                                model.setPraiseNumber(object.getString("PraiseNumber"));
                                model.setCommentNumber(object.getString("CommentNumber"));
                                model.setIf_Praise(object.getString("If_Praise"));
                                mList.add(model);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            ll_dialog.setVisibility(View.GONE);
                            mTalkAdapter.notifyDataSetChanged();
                        }
                    } else {
                        //没有说说
                    }
                    break;
                case GetMyTalkListFailed:
                    break;
            }
            return false;
        }
    });

    public static void startActivity(Context mContext, PersonalCenterBean user, boolean isScan) {
        Intent intent = new Intent(mContext, PersonalCenterActivity.class);
        intent.putExtra(Constants.INTENT_USER_BEAN, user);
        intent.putExtra(Constants.INTENT_IS_SCAN, isScan);
        mContext.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtils.i("isput" + "onCreate");
        setContentView(R.layout.activity_personal_center);
        ActivityHelper.getInstance().addActivity(PersonalCenterActivity.this);
        mUser = (PersonalCenterBean) getIntent().getSerializableExtra(Constants.INTENT_USER_BEAN);
        isScan = getIntent().getBooleanExtra(Constants.INTENT_IS_SCAN, false);
        initView();
        loadInfo();
        initSexDialog();
        initPhotoDialog();
        getMyTalkList();
    }

    private void initView() {
        mTalkView = findViewById(R.id.mTalkView);
        item_empty_view = findViewById(R.id.item_empty_view);
        ll_dialog = findViewById(R.id.ll_dialog);

        mLodingView = new LodingView(this);
        mLodingView.setLodingText("正在更新用户信息...");
        ib_return = findViewById(R.id.ib_return);
        ib_return.setOnClickListener(this);
        tv_user_sex = findViewById(R.id.tv_user_sex);

        ib_scan = findViewById(R.id.ib_scan);
        ib_scan.setOnClickListener(this);
        ib_editable = findViewById(R.id.ib_editable);
        ib_editable.setOnClickListener(this);
        headImage = findViewById(R.id.head_image);
        personal_focus_on = findViewById(R.id.personal_focus_on);
        personal_focus_on.setOnClickListener(this);
        personal_talk = findViewById(R.id.personal_talk);
        personal_talk.setOnClickListener(this);
        et_user_name = findViewById(R.id.et_user_name);
        et_user_remark = findViewById(R.id.et_user_remark);
        tv_stockAge = findViewById(R.id.tv_stockAge);
        tv_follow_number = findViewById(R.id.tv_follow_number);
        tv_fans_number = findViewById(R.id.tv_fans_number);
        tv_talk_number = findViewById(R.id.tv_talk_number);
        tv_coin_number = findViewById(R.id.tv_coin_number);
        tv_sumMoney = findViewById(R.id.tv_sumMoney);
        ib_qr = findViewById(R.id.ib_qr);
        ib_qr.setOnClickListener(this);
        if (mUser.getId() == Integer.parseInt(SpUtils.getInstance().getString(Constants.SP_USER_ID, ""))) {
            personal_focus_on.setVisibility(View.GONE);
            personal_talk.setVisibility(View.GONE);
            ib_editable.setVisibility(View.VISIBLE);
        } else {
            ib_scan.setVisibility(View.GONE);
            ib_qr.setVisibility(View.GONE);
            if (mUser.getIf_Follow().equals("true")) {
                personal_focus_on.setChecked(true);
                personal_focus_on.setText("已关注");
            }
        }
        mTalkView.setLayoutManager(new LinearLayoutManager(this));
        mTalkView.addItemDecoration(new DividerItemDecoration(this,
                DividerItemDecoration.VERTICAL));
        //取消动画
        ((SimpleItemAnimator) mTalkView.getItemAnimator()).setSupportsChangeAnimations(false);
        mTalkAdapter = new CommonAdapter<>(mList, new CommonAdapter.OnBindDataListener<TalkModel>() {
            @Override
            public void onBindViewHolder(final TalkModel model, final CommonViewHolder viewHolder, int type, int position) {
                final ImageView praised = viewHolder.getView(R.id.iv_praised);
                if (praiseDatas.size() > 0) {
                    praiseDatas.clear();
                }
                if (CancelPraiseDatas.size() > 0) {
                    CancelPraiseDatas.clear();
                }
                if (!model.getIf_Praise().equals("False")) {
                    praised.setImageResource(R.drawable.praise_checked);
                    praised.setTag("checked");
                }
                final int[] praise = {Integer.parseInt(model.getPraiseNumber())};
                praised.setOnClickListener(new View.OnClickListener() {
                    //点赞事件
                    @Override
                    public void onClick(View v) {
                        if (praised.getTag().equals("unchecked")) {
                            praised.setImageResource(R.drawable.praise_checked);
                            praise[0] += 1;
                            viewHolder.setText(R.id.tv_praise_number, "" + praise[0]);
                            praised.setTag("checked");
                            //TalkId=***&UserId=***
                            praiseDatas.put("TalkId", String.valueOf(model.getId()));
                            praiseDatas.put("UserId", SpUtils.getInstance().getString(Constants.SP_USER_ID, ""));
                            OkHttpUtils.getInstance().Post(SendTalkPraiseUrl, null,
                                    praiseDatas, null, null,
                                    new OkHttpUtils.okHttpListener() {
                                        @Override
                                        public void OnSuccess(String s, int code) throws JSONException {
                                            LogUtils.i("点赞事件处理" + "点赞成功" + s);
                                        }

                                        @Override
                                        public void OnFailed(String s) {
                                            LogUtils.i("点赞事件处理" + "点赞失败");
                                        }
                                    });
                        } else if (praised.getTag().equals("checked")) {
                            LogUtils.i("点赞事件处理" + "取消点赞");
                            praised.setImageResource(R.drawable.praise_unchecked);
                            praise[0] -= 1;
                            viewHolder.setText(R.id.tv_praise_number, "" + praise[0]);
                            praised.setTag("unchecked");
                            //TalkId=***&UserId=***
                            CancelPraiseDatas.put("TalkId", String.valueOf(model.getId()));
                            CancelPraiseDatas.put("UserId", SpUtils.getInstance().getString(Constants.SP_USER_ID, ""));
                            OkHttpUtils.getInstance().Post(CancelTalkPraiseURl, null,
                                    CancelPraiseDatas, null, null, new OkHttpUtils.okHttpListener() {
                                        @Override
                                        public void OnSuccess(String s, int code) throws JSONException {
                                            LogUtils.i("点赞事件处理" + "取消点赞成功" + s);
                                        }

                                        @Override
                                        public void OnFailed(String s) {
                                            LogUtils.i("点赞事件处理" + "取消点赞失败");
                                        }
                                    });

                        }
                    }
                });

                viewHolder.setImageUrl(PersonalCenterActivity.this, R.id.ci_photo, model.getImageUrl());
                viewHolder.setText(R.id.tv_username, model.getUsername());
                viewHolder.setText(R.id.tv_stockAge, "股龄" + model.getStockAge());
                viewHolder.setText(R.id.tv_time, model.getTalkTime());
                viewHolder.setText(R.id.iv_read_number, "浏览" + model.getReadNumber() + "次");
                viewHolder.setText(R.id.tv_praise_number, model.getPraiseNumber());
                viewHolder.setText(R.id.tv_comment_number, model.getCommentNumber());
                viewHolder.setText(R.id.tv_content, model.getContent());
                //判断是否含有图片的说说
                if (model.getPictureUrl().equals("null")) {
                    viewHolder.getView(R.id.iv_img).setVisibility(View.GONE);
                } else {
                    viewHolder.getView(R.id.iv_img).setVisibility(View.VISIBLE);
                    viewHolder.setImageUrl(PersonalCenterActivity.this, R.id.iv_img, model.getPictureUrl());
                    viewHolder.getView(R.id.iv_img).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            ImagePreviewActivity.startActivity(
                                    PersonalCenterActivity.this, true, model.getPictureUrl());
                        }
                    });
                }
                viewHolder.getView(R.id.ci_photo).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        queryUserInfo(model.getUserId());
                    }
                });

            }

            @Override
            public int getLayoutId(int type) {
                return R.layout.community_list_item;
            }
        });
        mTalkView.setAdapter(mTalkAdapter);
    }

    private void queryUserInfo(int userId) {
        String url = "http://119.23.221.142/api/user/GetHomePage?UserId=" + userId
                + "&MyId=" + SpUtils.getInstance().getString(Constants.SP_USER_ID, "");
        LogUtils.i(url);
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            Message message = mHandler.obtainMessage();

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                LogUtils.i(LogTag + s);
                PersonalCenterBean bean = new Gson().fromJson(s, PersonalCenterBean.class);
                message.what = QUERY_USER_CODE;
                message.obj = bean;
                mHandler.sendMessage(message);
            }

            @Override
            public void OnFailed(String s) {
                message.what = 404;
                message.obj = s;
                mHandler.sendMessage(message);
            }
        });
    }

    /**
     * 头像选择
     */
    private void initPhotoDialog() {
        mPhotoDialog = DialogManager.getInstance().initView(this, R.layout.dialog_select_photo, Gravity.BOTTOM);
        tv_camera = mPhotoDialog.findViewById(R.id.tv_camera);
        tv_ablum = mPhotoDialog.findViewById(R.id.tv_ablum);
        tv_photo_cancel = mPhotoDialog.findViewById(R.id.tv_cancel);

        tv_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isPut = true;
                DialogManager.getInstance().hide(mPhotoDialog);
                FileHelper.getInstance().toCamera(PersonalCenterActivity.this);
            }
        });
        tv_ablum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isPut = true;
                DialogManager.getInstance().hide(mPhotoDialog);
                FileHelper.getInstance().toAlbum(PersonalCenterActivity.this);
            }
        });
        tv_photo_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DialogManager.getInstance().hide(mPhotoDialog);
            }
        });
    }

    /**
     * 性别选择
     */
    private void initSexDialog() {
        mSexDialog = DialogManager.getInstance().initView(this, R.layout.dialog_select_sex, Gravity.BOTTOM);
        tv_boy = mSexDialog.findViewById(R.id.tv_boy);
        tv_girl = mSexDialog.findViewById(R.id.tv_girl);
        tv_sex_cancel = mSexDialog.findViewById(R.id.tv_cancel);

        tv_boy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DialogManager.getInstance().hide(mSexDialog);
                tv_user_sex.setText("男");
            }
        });
        tv_girl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DialogManager.getInstance().hide(mSexDialog);
                tv_user_sex.setText("女");
            }
        });
        tv_sex_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DialogManager.getInstance().hide(mSexDialog);
            }
        });
    }

    /**
     * 加载个人信息
     */
    private void loadInfo() {
        //初始数据
        tv_user_sex.setText(mUser.getGender());
        imageUrl = mUser.getImageUrl();
        GlideHelper.loadUrl(this, mUser.getImageUrl(), headImage);
        et_user_name.setText(mUser.getUsername());
        if (!TextUtils.isEmpty(mUser.getRemark())) {
            et_user_remark.setText(mUser.getRemark());
        }
        tv_stockAge.setText(mUser.getStockAge());
        tv_follow_number.setText(mUser.getFollowNumber());
        tv_fans_number.setText(mUser.getFansNumber());
        tv_talk_number.setText(mUser.getTalkNumber());
        tv_coin_number.setText(mUser.getCoinNumber());
        tv_sumMoney.setText(mUser.getSumMoney());

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.head_image:
                DialogManager.getInstance().show(mPhotoDialog);
                break;
            case R.id.tv_user_sex:
                DialogManager.getInstance().show(mSexDialog);
                break;
            case R.id.ib_return:
                finish();
                break;
            case R.id.ib_scan:
                Intent intent = new Intent(this, QrCodeActivity.class);
                startActivityForResult(intent, REQUEST_CODE);
                break;
            case R.id.personal_talk:
                ChatActivity.startActivity(this, String.valueOf(mUser.getId()), mUser.getUsername(), mUser.getImageUrl());
                break;
            case R.id.personal_focus_on:
                if (personal_focus_on.getText().equals("已关注")) {
                    personal_focus_on.setText("关注");
                } else {
                    AddFollow(Integer.parseInt(SpUtils.getInstance().getString(Constants.SP_USER_ID, "")), mUser.getId());
                    personal_focus_on.setText("已关注");
                }
                break;
            case R.id.ib_editable:
                if (ib_editable.getTag().equals("false")) {
                    ib_editable.setTag("true");
                    ib_editable.setBackgroundResource(R.drawable.commit_white);
                    headImage.setClickable(true);
                    tv_user_sex.setClickable(true);
                    headImage.setOnClickListener(this);
                    tv_user_sex.setOnClickListener(this);
                    et_user_name.setEnabled(true);
                    et_user_remark.setEnabled(true);
                    Toast.makeText(this, "可编辑", Toast.LENGTH_SHORT).show();
                } else {
                    ib_editable.setTag("false");
                    headImage.setClickable(false);
                    tv_user_sex.setClickable(false);
                    et_user_name.setEnabled(false);
                    et_user_remark.setEnabled(false);
                    ib_editable.setBackgroundResource(R.drawable.modification_white);
                    mLodingView.show();
                    upDateUserInfo();
                    Toast.makeText(this, "提交成功", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.ib_qr:
                MyQRCodeActivity.startActivity(this, mUser);
                break;
        }
    }

    /**
     * 更新用户信息
     */
    private void upDateUserInfo() {
        String urlRoot = "http://119.23.221.142/api/user/ChangePersonalInfo?";
        Map<String, String> datas = new HashMap<>();
        datas.put("UserId", SpUtils.getInstance().getString(Constants.SP_USER_ID, ""));
        datas.put("ImageUrl", imageUrl);
        datas.put("Username", et_user_name.getText().toString());
        if (tv_user_sex.getText().toString().equals("男")) {
            datas.put("Gender", "1");
        } else {
            datas.put("Gender", "0");
        }
        datas.put("Remark", et_user_remark.getText().toString());
        OkHttpUtils.getInstance().Post(urlRoot, null, datas,
                null, null, new OkHttpUtils.okHttpListener() {
                    Message message = mHandler.obtainMessage();

                    @Override
                    public void OnSuccess(String s, int code) throws JSONException {
                        JSONObject object = new JSONObject(s);
                        if (object.getString("code").equals("200")) {
                            message.what = UPDATESUCCESS;
                            mHandler.sendMessage(message);
                        } else {
                            message.what = UPDATEFailed;
                            mHandler.sendMessage(message);
                        }
                    }

                    @Override
                    public void OnFailed(String s) {

                    }
                });


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //处理二维码的返回

        if (requestCode == REQUEST_CODE) {
            LogUtils.i(LogTag + "onActivityResult");
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                LogUtils.i(LogTag + bundle);
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    LogUtils.i(LogTag + "二维码结果" + result);
                    //Meet#c7a9b4794f
                    if (!TextUtils.isEmpty(result)) {
                        //是我们自己的二维码
                        if (result.startsWith("Meet")) {
                            String[] split = result.split("#");
                            LogUtils.i("split:" + split.toString());
                            if (split != null && split.length >= 2) {
                                try {
                                    LogUtils.i(LogTag + split[1]);
                                    queryUser(split[1]);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        } else {
                            Toast.makeText(this, "错误的二维码", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(this, "解析二维码失败", Toast.LENGTH_SHORT).show();
                    }

                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(this, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
        //处理相机和相册的返回
        if (resultCode == RESULT_OK) {
            if (requestCode == FileHelper.CAMEAR_REQUEST_CODE) {
                isPut = true;
                FileHelper.getInstance().startPhotoZoom(this, FileHelper.getInstance().getTempFile());
                uploadPhotoFile = FileHelper.getInstance().getTempFile();
            } else if (requestCode == FileHelper.ALBUM_REQUEST_CODE) {
                isPut = true;
                flag = 0;
                Uri uri = data.getData();
                if (uri != null) {
                    String path = FileHelper.getInstance().getRealPathFromURI(this, uri);
                    if (!TextUtils.isEmpty(path)) {
                        uploadPhotoFile = new File(path);
                        FileHelper.getInstance().startPhotoZoom(this, uploadPhotoFile);
                    }
                }
            } else if (requestCode == FileHelper.CAMERA_CROP_RESULT) {
                uploadPhotoFile = new File(FileHelper.getInstance().getCropPath());
                LogUtils.i("uploadPhotoFile:" + uploadPhotoFile.getPath());
            }
            if (uploadPhotoFile != null) {
                if (flag == 1) {
                    flag = 0;
                    LogUtils.i(LogTag + "上传图片");
                    Bitmap bitmap = BitmapFactory.decodeFile(uploadPhotoFile.getPath());
                    headImage.setImageBitmap(bitmap);
                    BmobManager.getInstance().uploadHeadPhoto(uploadPhotoFile, new BmobManager.OnUploadPhotoListener() {
                        @Override
                        public void OnSuccess(String url) {
                            LogUtils.i(LogTag + url);
                            imageUrl = url;
                            LogUtils.i("uploadPhotoFile:" + imageUrl);
                        }

                        @Override
                        public void OnFailed(BmobException e) {
                            Toast.makeText(PersonalCenterActivity.this, "上传失败" + e.toString(), Toast.LENGTH_SHORT).show();
                        }
                    });

                } else {
                    flag = 1;
                }

            }
        }
    }

    private void queryUser(String userId) {
        String url = "http://119.23.221.142/api/user/GetHomePage?UserId=" + userId;
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            Message message = mHandler.obtainMessage();

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                LogUtils.i("PersonalCenterActivity:" + s);
                PersonalCenterBean bean = new Gson().fromJson(s, PersonalCenterBean.class);
                message.what = code;
                message.obj = bean;
                mHandler.sendMessage(message);
            }

            @Override
            public void OnFailed(String s) {
                message.what = 404;
                message.obj = s;
                mHandler.sendMessage(message);
            }
        });
    }

    /**
     * 关注他人
     * FollowingId（自己的Id）和FollowedId（被关注者的Id））
     * POST
     */
    private void AddFollow(int FollowingId, int FollowedId) {
        String urlRoot = "http://119.23.221.142/api/user/AddFollow?";
        Map<String, String> datas = new HashMap<String, String>();
        datas.put("FollowingId", String.valueOf(FollowingId));
        datas.put("FollowedId", String.valueOf(FollowedId));
        OkHttpUtils.getInstance().Post(urlRoot, null, datas,
                null, null, new OkHttpUtils.okHttpListener() {
                    @Override
                    public void OnSuccess(String s, int code) throws JSONException {
                        LogUtils.i(LogTag + s);
                    }

                    @Override
                    public void OnFailed(String s) {

                    }
                });
    }

    private void getMyTalkList() {
        String url = "http://119.23.221.142/api/talk/GetMyTalkList?UserId=" + mUser.getId()
                + "&MyId=" + SpUtils.getInstance().getString(Constants.SP_USER_ID, "");
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            Message message = mHandler.obtainMessage();

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                JSONObject object = new JSONObject(s);
                if (object.getString("code").equals("200")) {
                    message.what = GetMyTalkListSuccess;
                    message.obj = object.getJSONArray("data");
                    mHandler.sendMessage(message);
                } else {
                    message.what = GetMyTalkListFailed;
                    mHandler.sendMessage(message);
                }
            }

            @Override
            public void OnFailed(String s) {
                message.what = 404;
                message.obj = s;
                mHandler.sendMessage(message);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtils.i("isput" + isPut);
        if (isPut) {
            //没有提交，只是选择图片返回
            ib_editable.setTag("true");
            ib_editable.setBackgroundResource(R.drawable.commit_white);
            headImage.setClickable(true);
            tv_user_sex.setClickable(true);
            headImage.setOnClickListener(this);
            tv_user_sex.setOnClickListener(this);
            et_user_name.setEnabled(true);
            et_user_remark.setEnabled(true);
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
//        RefWatcher refWatcher = BaseApp.getRefWatcher(this);//1
//        refWatcher.watch(this);
    }
}
